<?php

namespace app\api\controller\user;

use app\api\controller\Controllers;
use app\api\service\user\User as UserService;
use app\api\service\user\OAuth2 as OAuth2Service;
use app\api\service\common\Token;
use think\Request;

class User extends Controllers
{

    /**
     * 用户认证
     * @param UserService $service
     * @throws \app\exceptions\OrdinaryException
     * @return \think\Response
     */
    public function oAuth2( OAuth2Service $service, UserService $userService, Token $token )
    {
        $get = $this->request->only(['code','state'], 'get');
        $userCredentials = $service->handler($get['code'], $get['state']);
        // 注册或绑定用户
        $unionid = get($userCredentials, 'unionid');
        $binding = $userService->binding($unionid, $userCredentials['openid'], $get['state']);
        if ( 200 === $binding['code'] ) {
            return success([
                'token' => $token->get($binding['data']),
                'nickname' => $binding['data']['nickname'],
                'headimg_url' => $binding['data']['headimg_url']
            ]);
        }
        return failed($binding['message']);
    }

    /**
     * 添加用户信息
     *
     * @return \think\Response
     */
    public function info(Request $request, UserService $service)
    {
        $post = $this->request->only(['nickname','headimg_url'], 'post');
        $uid = $request->userInfo['id'];
        $saveUserInfo = $service->saveUserInfo($post, $uid);
        if ( $saveUserInfo ) {
            return success();
        }
        return failed('用户信息插入失败');
    }

}
